class LotteryBallBaseController {
    constructor( $rootScope, $scope,$state, $interval,$timeout, lotteryService,AccountService, constant) {
        Object.assign(this, {$rootScope, $scope,$state,$interval,$timeout, lotteryService,AccountService, constant});
        this.$rootScope.isAtLotteryPage = true;
        let lotteryType = $state.params.type;
        this.lotteryType = lotteryType;
        this.$rootScope.lotteryType = lotteryType;
        this.lotteryService.lotteryType = lotteryType;
        this.$rootScope.urlPrefixEncoded = encodeURI(constant.urlPrefix);
        this.$rootScope.awardtipMarquee=false;
        this.times = 1;
        //警告窗口
        this.alert ={};
        this.betCalcInfo = {
            times: 1,//倍数
            itemCount: 0,//注数
            totalPrice: 0, //投注金额
            playid:0,
            lotteryType,
            betCalcInfoList: Array()
        }
        let lotteryList = this.constant.lotteryList.filter((lottery) => lottery["key"]== lotteryType);
        //选择的彩票信息
        this.lotteryInfo = lotteryList[0];
        this.currentLotteryTypeLevel1Info = this.lotteryInfo.typeLevel1[0];
        this.currentLotteryTypeLevel2Info = this.currentLotteryTypeLevel1Info.typeLevel2[0];
        //初始化彩种的赔率
        this.initOrRefreshLotteryOdds();
       // console.log(this.currentLotteryTypeLevel2Info);
        this.typeLevel2ButtonActiveClass = "btn-warning";
        //缓存投注列表
        this.betTicketCodeCache={
            totalBets:0,
            totalPrice:0,
            betTicketCodeCacheList:new Array()
        }
        //开奖号码列表
        this.winingNumList=[];
        //中奖用户列表
        this.wonUserList =[];
        this.winningNumAndWonUsers();
    }

    /**
     * 刷新账户信息
     */
    refreshAccount () {
        let self = this;
        self.AccountService.getAccountInfo({ignoreLoadingBar: true}).then(accountinfo_success)
            .catch(accountinfo_error);

        function accountinfo_success(data) {
            self.$rootScope.lotteryAccountInfo = data;
        };

        function accountinfo_error(reason) {
            console.log(`AccountService.getAccountInfo:${JSON.stringify(reason)}`);
        };
    }

    /**
     * 初始化或刷新赔率。
     */
    initOrRefreshLotteryOdds(){
        let self = this;
        self.lotteryService.get_award_description({lot_type:self.lotteryType},{ignoreLoadingBar: true}).then(get_award_description_success)
            .catch(get_award_description_error);

        function get_award_description_success(data) {
            let longHuHeOdds = ""; // 龙虎和的赔率专门填写
            let longHuHeOddsMap = {};
            let lotteryLevel1List =undefined;
            let tmpLongHuHePlay = undefined;
            self.constant.lotteryList.forEach(function (lottery,index,array) {
                if(lottery.key==self.lotteryType){
                    lotteryLevel1List =lottery;
                    return;
                }
            })
            if(lotteryLevel1List){
                lotteryLevel1List.typeLevel1.forEach(function (lotteryLevel2List,i,level1Array) {
                    lotteryLevel2List.typeLevel2.forEach(function (play,k,level2Array) {
                        let playId = parseInt(play.key);
                        if(self.lotteryType == 'cqssc' && parseInt(play.key) == 801){
                            tmpLongHuHePlay = play;
                        }
                        data.data.data_list.forEach(function (item,j,array) {
                            if(playId == item.play_id ){
                                if(self.lotteryType == 'cqssc' && playId == 801){ //如果是否
                                    if(item.play_name.indexOf("（龙）")!=-1){
                                        longHuHeOdds += "龙("+item.prize+"),";
                                        longHuHeOddsMap["龙"] = item.prize;
                                    }else if(item.play_name.indexOf("（虎）")!=-1){
                                        longHuHeOdds += "虎("+item.prize+"),"
                                        longHuHeOddsMap["虎"] = item.prize;
                                    }else if(item.play_name.indexOf("（和）")!=-1){
                                        longHuHeOdds += "和("+item.prize+"),"
                                        longHuHeOddsMap["和"] = item.prize;
                                    }
                                }else{
                                    play.prize = item.prize;
                                }
                            }
                            return;
                        });
                    });
                });
                longHuHeOdds = longHuHeOdds.substr(0,longHuHeOdds.length-1);
                tmpLongHuHePlay.prize=longHuHeOdds;
                tmpLongHuHePlay.prizeMap = longHuHeOddsMap;
                //console.log(lotteryLevel1List);
            }
        };

        function get_award_description_error(reason) {
            console.log(`lotteryService.get_award_description:${JSON.stringify(reason)}`);
        };
    }

    /**
     * 开奖公告和中奖排行
     */
    winningNumAndWonUsers(){
        let self = this;
        self.winningNum();
        self.wonUsers();
    }

    winningNum(){
        let self = this;
        self.lotteryService.getWinningNum(self.lotteryType).then(winning_num_success).catch(winning_num_error);
        function winning_num_success(data) {
            if(self.lotteryType=='xysc'){
                self.winingNumList = data.data.data_list.slice(0,3);
            }else{
                self.winingNumList = data.data.data_list.slice(0,5);
            }
        };
        function winning_num_error(reason) {
            console.log("winningNumAndWonUsers().: "+JSON.stringify(reason));
        };
        self.$timeout(function () {
            self.winningNum();
        },10*60*1000);
    }

    wonUsers(){
        let self = this;
        self.lotteryService.getWonUserList(self.lotteryType).then(won_users_success).catch(won_users_error);
        function won_users_success(data) {
            self.wonUserList = data.data.data_list.slice(0,5);
            // console.log("wonUsers().: "+JSON.stringify(self.wonUserList));
        };
        function won_users_error(reason) {
            console.log("wonUsers().: "+JSON.stringify(reason));
        };
        self.$timeout(function () {
            self.winningNum();
        },10*60*1000);
    }

    initBetCalcInfo(){
        this.betCalcInfo = {
            times: 1,//倍数
            itemCount: 0,//注数
            totalPrice: 0, //投注金额
            playId:0,
            lotteryType:this.lotteryType,
            betCalcInfoList: Array()
        };
    }


    /**
     * 选择所有球
     * @param ballsRowKey 球行的关键字，如：thousand，hundred
     */
    selectAllBalls(typeLevel2, ballsRowKey) {
        let balls = $("div." + typeLevel2).find("#ul_balls_" + ballsRowKey + ">li");
        balls.addClass("selected");
        this.betCalcAmount(true);
    }

    /**
     * 选择大号的球
     * @param ballsRowKey 球行的关键字，如：thousand，hundred
     */
    selectBigBalls(typeLevel2, ballsRowKey) {
        let self = this;
        let begin = 5;
        if(self.lotteryType == 'gd11x5'){
            begin = 6
        }else if(self.lotteryType == 'xysc'){
            begin = 6
        }
        let balls = $("div." + typeLevel2).find("#ul_balls_" + ballsRowKey + ">li");
        balls.removeClass("selected");
        balls.each((index, ele) => {
            let ballNumer = Number.parseInt($(ele).text());
            if (ballNumer >= begin) {
                $(ele).addClass("selected");
            }
        });
        this.betCalcAmount(true);
    }

    /**
     * 选择小号的球
     * @param ballsRowKey 球行的关键字，如：thousand，hundred
     */
    selectSmallBalls(typeLevel2, ballsRowKey) {
        let balls = $("div." + typeLevel2).find("#ul_balls_" + ballsRowKey + ">li");
        balls.removeClass("selected");
        balls.each((index, ele) => {
            let ballNumer = Number.parseInt($(ele).text());
            if (ballNumer <= 4) {
                $(ele).addClass("selected");
            }
        });
        this.betCalcAmount(true);
    }

    /**
     * 选择奇数球
     * @param ballsRowKey 球行的关键字，如：thousand，hundred
     */
    selectOddBalls(typeLevel2, ballsRowKey) {
        let balls = $("div." + typeLevel2).find("#ul_balls_" + ballsRowKey + ">li");
        balls.removeClass("selected");
        balls.each((index, ele) => {
            let ballNumer = Number.parseInt($(ele).text());
            if (ballNumer % 2 == 1) {
                $(ele).addClass("selected");
            }
        });
        this.betCalcAmount(true);
    }

    /**
     * 选择偶数球
     * @param ballsRowKey 球行的关键字，如：thousand，hundred
     */
    selectEvenBalls(typeLevel2, ballsRowKey) {
        let balls = $("div." + typeLevel2).find("#ul_balls_" + ballsRowKey + ">li");
        balls.removeClass("selected");
        balls.each((index, ele) => {
            let ballNumer = Number.parseInt($(ele).text());
            if (ballNumer % 2 == 0) {
                $(ele).addClass("selected");
            }
        });
        this.betCalcAmount(true);
    }

    /**
     * 清除选择的球
     * @param ballsRowKey 球行的关键字，如：thousand，hundred
     */
    selectCleanBalls(typeLevel2, ballsRowKey) {
        let balls = $("div." + typeLevel2).find("#ul_balls_" + ballsRowKey + ">li");
        balls.removeClass("selected");
        this.betCalcAmount(true)
    }

    clearAllSelectedBalls(clac) {
        let balls = $("div.typeLevel2Area .ul_balls>li");
        balls.removeClass("selected");
        this.betCalcAmount(clac)
    }

    /***
     * 检查倍数
     * @param event
     */
    checkTimesValue(event){
        if(this.betCalcInfo.times>=100000){
            layer.open({
               icon:2,
               title:"错误！",
               content:"对不起，不允许倍数超过十万倍",
               btn:["好的"],
               yes:function (index,layerno) {
                   layer.close(index);
               }
           });
            this.betCalcInfo.times=99999;
        }
        this.betCalcAmount(true)
    }
    /**
     * 增加注数
     */
    addLotteryTimes() {
        let reg = /\d+/
        this.betCalcInfo.times = this.betCalcInfo.times && reg.exec(this.betCalcInfo.times)? parseInt(this.betCalcInfo.times)+1:1;
        if(this.betCalcInfo.times>=100000){
            layer.open({
               icon:2,
               title:"错误！",
               content:"对不起，不允许倍数超过十万倍",
               btn:["好的"],
               yes:function (index,layerno) {
                   layer.close(index);
               }
           });
            this.betCalcInfo.times=99999;
        }
        this.betCalcAmount(true)
    }

    /**
     * 减少注数
     */
    minusLotteryTimes() {
        let reg = /\d+/
        this.betCalcInfo.times = this.betCalcInfo.times && reg.exec(this.betCalcInfo.times)? parseInt(this.betCalcInfo.times)-1:1;
        if(this.betCalcInfo.times<=0){
            this.betCalcInfo.times =1;
        }
        this.betCalcAmount(true)
    }
    /**
     * 切换一级彩票分类
     * @param typeLevel1Key
     */
    changeTypeLevel1Info(typeLevel1Key){
        let typeLevel1List =  this.lotteryInfo.typeLevel1.filter((typeLevel1t) => typeLevel1t["key"]== typeLevel1Key);
        //选择的彩票信息
        this.currentLotteryTypeLevel1Info = typeLevel1List[0];
        console.log("currentLotteryTypeLevel1Info: "+JSON.stringify(this.currentLotteryTypeLevel1Info));
    }

    /**
     * 切换二级彩票分类
     * @param typeLevel2Key
     */
    changeTypeLevel2Info(typeLevel2Key){
        let typeLevel2List =  this.currentLotteryTypeLevel1Info.typeLevel2.filter((typeLevel2t) => typeLevel2t["key"]== typeLevel2Key);
        //选择的彩票信息
        this.currentLotteryTypeLevel2Info = typeLevel2List[0];
        //console.log("currentLotteryTypeLevel2Info: "+JSON.stringify(this.currentLotteryTypeLevel2Info));
    }
    /**
     * 切换一级类型
     * @param typeLevel1Key
     */
    changeTypeLevel1Tab(typeLevel1Key) {
        $("div.typeLevel1VArea").hide();
        let typeLevel1EleList = $("div#" + typeLevel1Key);
        typeLevel1EleList.show();
        this.changeTypeLevel1Info(typeLevel1Key);//切换一级彩票分类
        let defaultActiveLevel2Tab = typeLevel1EleList.find("button.typelevel2Button").first();
        let typeLevel2Key = defaultActiveLevel2Tab.data("typelevel2");
        defaultActiveLevel2Tab.addClass(this.typeLevel2ButtonActiveClass);
        this.changeTypeLevel2Tab(typeLevel1Key, defaultActiveLevel2Tab.attr("data-typeLevel2"));
        this.changeTypeLevel2Info(typeLevel2Key);
    }

    /**
     * 切换二级类型
     * @param typeLevel1Key
     * @param typeLevel2Key
     */
    changeTypeLevel2Tab(typeLevel1Key, typeLevel2Key) {
        let typeLevel2AreaEleList = $("div.typeLevel2Area");
        typeLevel2AreaEleList.removeClass("show").addClass("hide");
        $("div." + typeLevel2Key).removeClass("hide").addClass("show");
        this.changeTypeLevel2Info(typeLevel2Key);

        let balls = typeLevel2AreaEleList.find("ul.ul_balls > li");
        balls.removeClass("selected");

        $("button.typelevel2Button").removeClass(this.typeLevel2ButtonActiveClass);
        $("button." + typeLevel2Key).addClass(this.typeLevel2ButtonActiveClass);
    }

    /**
     * 选择某个球
     * @param ballElement 球元素
     */
    selectABall($event) {
        angular.element($event.target).toggleClass("selected");
        this.betCalcAmount(true);
    }

    /**
     * 计算投注金额和预计奖金
     * @param unit
     */
    betCalcAmount(calc) {
        let self =this;
        if(arguments&&arguments.length>0&&calc==true){
            let ticketcodeList = self.currentLotteryTypeLevel2Info.populateNums(self,self.currentLotteryTypeLevel2Info,self.typeLevel2ButtonActiveClass);
            let betCalcAmount = {"ticketcode":ticketcodeList};
            //console.log(betCalcAmount);
            this.lotteryService.getBetCalcAmount(betCalcAmount).then(_success).catch(_error);
            function _success(data) {
                ticketcodeList[0].totalPrice=data.total_price;
                ticketcodeList[0].betTime = Date.now();
                ticketcodeList[0].itemCount= data.item_count;
                ticketcodeList[0].prize= self.currentLotteryTypeLevel2Info.prize;
                self.betCalcInfo.itemCount= data.item_count;
                self.betCalcInfo.totalPrice= data.total_price;
                //console.log(data);
            }
            function _error(reason) {
                console.log("betCalcAmount()=>lotteryService.getBetCalcAmount() "+reason);
            }
        }
    }

    /**
     * 投注
     */
    betImmediately(){
        let self = this;
        let ticketcodeEle = {}
        ticketcodeEle.playid =self.betCalcInfo.playid;
        ticketcodeEle.code =self.betCalcInfo.ticketcode;
        ticketcodeEle.multiple =self.betCalcInfo.times;
        let ticketcode = [ticketcodeEle];
        let betBallsInfo = {ticketcode,totalamount:self.betCalcInfo.totalPrice};
        // betBallsInfo.
        this.lotteryService.bet(betBallsInfo).then(_success).catch(_error);
        function _success(data) {
            self.initBetCalcInfo();
            self.clearAllSelectedBalls(false);
            layer.open({
                   icon:0,
                   title:"信息！",
                   content:"投注成功",
                   btn:["好的"],
                   yes:function (index,layerno) {
                       layer.close(index);
                   }
               });
        }
        function _error(reason) {
             let type = typeof reason;
        	layer.open({
                   icon:2,
                   title:"错误！",
                   content:type=='object'?reason.text:reason,
                   btn:["好的"],
                   yes:function (index,layerno) {
                       layer.close(index);
                   }
               });
        }
    }

    /**
     * 确认是否投注
     */
    betFromCacheConfirm(){
        let  self = this;
        if(self.betTicketCodeCache.betTicketCodeCacheList.length==0){
            layer.open({
               icon:0,
               title:"注意！",
               content:"请先选择号码，再进行投入！",
               btn:["好的"],
               yes:function (index,layerno) {
                   layer.close(index);
               }
           });
        }else{
            let warning = "<div class='pull-right'><span style='color: red;font-weight: 700;'>*每期最高中奖利润100000元</span>&nbsp;&nbsp;是否确定投注？</div>";
            let table = "<table class='table table-width'><thead><tr><th width='15%'>玩法</th><th width='45%'>号码</th><th width='15%'>赔率</th><th width='5%'>注</th><th width='5%'>倍</th><th width='10%'>金额</th></tr></thead><tbody id='betBallsRow' style='background-color: #ffffff'></tbody></table>";
            let tableEle = $(table);
            let tbody = ('#betBallsRow',tableEle);
            self.betTicketCodeCache.totalPrice = 0;
            self.betTicketCodeCache.totalBets = 0;
            self.betTicketCodeCache.betTicketCodeCacheList.forEach(function (item, index, array) {
                self.betTicketCodeCache.totalPrice += item.totalPrice;
                self.betTicketCodeCache.totalBets += item.itemCount;
                tbody.append("<tr><td width='15%'>"+item.playName+"</td><td width='45%' class='custom-word-break'>"+item.code+"</td><td width='15%' class='custom-word-break'>"+item.prize+"</td><td width='5%'>"+item.itemCount+"</td><td width='5%'>"+item.multiple+"</td><td width='10%' style='color: red;font-weight: 700;'>￥"+item.totalPrice+"</td></tr>");
            });
            let total = "<div class='pull-right'>共计：<span style='color: red;font-weight: 700;'>"+self.betTicketCodeCache.totalBets+"</span>注，￥<span style='color: red;font-weight: 700;'>"+self.betTicketCodeCache.totalPrice+"</span></div>";
            let xTable = "<table width='100%' style='bottom: 10px;'><tr><td>"+total+"</td></tr><tr><td>"+warning+"</td></tr></table>";
            //console.log(tableEle[0].outerHTML);
            layer.open({
               title: '投注内容',
               area: ['550px', '350px'],
               content: tableEle[0].outerHTML+xTable,
               btn: ['确定', '取消'],
               btn1: function(index, layero){
                   //确认回调
                   //alert("btn1")
                   layer.close(index);
                   self.betFromCache();
               },
               btn2: function(index, layero){
                   //按钮【按钮二】的回调
                   //alert("btn2")
                   layer.close(index);
               }
           });
        }
    }

    /**
     * 从缓存中发起投注。
     */
    betFromCache(){
        let  self = this;
        if(self.betTicketCodeCache.betTicketCodeCacheList.length==0){
            layer.open({
               icon:0,
               title:"注意！",
               content:"请先选择号码，再进行投入！",
               btn:["好的"],
               yes:function (index,layerno) {
                   layer.close(index);
               },
               time:3000
           });
        }else{
            self.betTicketCodeCache.totalPrice = 0;
            self.betTicketCodeCache.totalBets = 0;
            let ticketcode = new Array();
            self.betTicketCodeCache.betTicketCodeCacheList.forEach(function (item, index, array) {
                self.betTicketCodeCache.totalPrice += item.totalPrice;
                self.betTicketCodeCache.totalBets += item.itemCount;
                ticketcode.push(item);
            });
            let betBallsInfo = {ticketcode,totalamount:self.betTicketCodeCache.totalPrice};
            self.lotteryService.getCurrentIssue(self.lotteryType)
                .then(_currentIssueSucc)
                .catch(_currentIssueError);

            function _currentIssueSucc(data) {
                if(data.message && data.message.code ==200){
                    self.lotteryService.lotteryIssueInfo =data;
                    self.lotteryService.setLotteryIssueInfo(data);
                    self.lotteryService.bet(betBallsInfo).then(bet_success).catch(bet_error);


                }else{
                    return self.$q.reject(data.message);
                }
            }

            function _currentIssueError(reason) {
                //弹出警告窗口
                console.log("LotteryService.getCurrentIssue() :"+JSON.stringify(reason));
                let type = typeof reason;
                layer.open({
                   icon:2,
                   title:"错误！",
                   content:type=='object'?reason.text:reason,
                   btn:["好的"],
                   yes:function (index,layerno) {
                       layer.close(index);
                   }
               });
            }

            function bet_success(data) {
                self.trashBetTicketCodeCache();
                layer.open({
                   icon:0,
                   title:"信息！",
                   content:"投注成功",
                   btn:["好的"],
                   yes:function (index,layerno) {
                       layer.close(index);
                   }
               });
                self.trashBetTicketCodeCache();
                self.refreshAccount ();
            }
            function bet_error(reason) {
                let type = typeof reason;
                layer.open({
                   icon:2,
                   title:"错误！",
                   content:type=='object'?reason.text:reason,
                   btn:["好的"],
                   yes:function (index,layerno) {
                       layer.close(index);
                   }
               });
            }
        }
    }

    /**
     * 添加到投注列表
     */
    addToBetCache(typeLevel2Key){
        let self = this;
        let canAddToCache = self.currentLotteryTypeLevel2Info.checkBeforeAddToCache(self,self.currentLotteryTypeLevel2Info,self.typeLevel2ButtonActiveClass);
        if(canAddToCache){
            if(self.betCalcInfo && self.betCalcInfo.betCalcInfoList  && self.betCalcInfo.betCalcInfoList.length > 0){
                self.betTicketCodeCache.totalPrice = 0;
                self.betTicketCodeCache.totalBets = 0;
                for(let i=0;i<self.betCalcInfo.betCalcInfoList.length; i++){
                    self.betTicketCodeCache.betTicketCodeCacheList.push(self.betCalcInfo.betCalcInfoList[i]);
                }
                self.betTicketCodeCache.betTicketCodeCacheList.forEach(function (item, index, array) {
                    self.betTicketCodeCache.totalPrice += item.totalPrice;
                    self.betTicketCodeCache.totalBets += item.itemCount;
                });
                self.initBetCalcInfo();
                self.clearAllSelectedBalls(false);
            }
        }
        console.log("betTicketCodeCacheList size:" + self.betTicketCodeCache.betTicketCodeCacheList.length +",betTicketCodeCacheList: "+JSON.stringify(self.betTicketCodeCache.betTicketCodeCacheList));
    }


    /**
     * 清空缓存
     */
    trashBetTicketCodeCache(){
        this.betTicketCodeCache={
            totalBets:0,
            totalPrice:0,
            betTicketCodeCacheList:new Array()
        }
    }

    /**
     * 删除一行
     * @param betTime
     */
    removeBetTicketCodeCacheRow(betTime){
        let self = this;
        self.betTicketCodeCache.betTicketCodeCacheList.forEach(function (item, index, array) {
           if(item.betTime==betTime){
               array.splice(index, 1);
           }
        });
        if(self.betTicketCodeCache.betTicketCodeCacheList.length==0){
            self.trashBetTicketCodeCache();
        }else{
            self.betTicketCodeCache.totalPrice = 0;
            self.betTicketCodeCache.totalBets = 0;
            self.betTicketCodeCache.betTicketCodeCacheList.forEach(function (item, index, array) {
                self.betTicketCodeCache.totalPrice += item.totalPrice;
                self.betTicketCodeCache.totalBets += item.itemCount;
            });
        }
    }
}

LotteryBallBaseController.$inject =["$rootScope", "$scope","$state", "$interval","$timeout", "LotteryService","AccountService", "Constant"];
export default LotteryBallBaseController;